#include "SrpcConfig.h"
#include "SrpcLogger.h"
#include <cstdio>
#include <functional>
#include <glog/logging.h>
#include <memory>

void SrpcConfig::LoadConfigFile(const std::string &config_file) {
  std::unique_ptr<FILE, std::function<void(FILE *)>> fp(
      fopen(config_file.c_str(), "r"), [](FILE *fp) { fclose(fp); });
  if (fp == nullptr) {
    SrpcLogger::ERROR("open config file fail. config file path: " +
                      config_file);
    exit(EXIT_FAILURE);
  }
  std::string read_buf;
  read_buf.resize(1024);
  while (fgets(&read_buf[0], 1024, fp.get()) != nullptr) {
    // 去除字符串前后的空格
    Trim(read_buf);
    // 忽略注释行(#)和空行
    if (read_buf[0] == '#' || read_buf.empty())
      continue;
    // 查找键值对分隔符 " = "
    int index = read_buf.find('=');
    if (index == -1)
      continue;
    // 提取键
    std::string key = read_buf.substr(0, index);
    Trim(key);
    // 查找行尾的换行符
    int endindex = read_buf.find('\n', index);
    // 提取值
    std::string value = read_buf.substr(index + 1, endindex - index - 1);
    Trim(value);
    // 存储配置项
    m_config_map.insert({key, value});
  }
}

std::string SrpcConfig::Load(const std::string &key) {
  auto it = m_config_map.find(key);
  if (it == m_config_map.end()) {
    return "";
  }
  return it->second;
}

void SrpcConfig::Trim(std::string &read_buf) {
  // 删除头部空格
  int index = read_buf.find_first_not_of(' ');
  if (index != -1) {
    read_buf = read_buf.substr(index, read_buf.length() - index);
  }
  // 删除尾部空格
  index = read_buf.find_last_not_of(' ');
  if (index != -1) {
    read_buf = read_buf.substr(0, index + 1);
  }
}